package org.itboys.seller.service;

import org.apache.commons.collections.CollectionUtils;
import org.itboys.seller.constant.CaliforniaSiteConstant;
import org.itboys.seller.mapper.WalletMapper;
import org.itboys.seller.meta.Wallet;
import org.itboys.seller.meta.WalletExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hzliangchong1@corp.netease.com
 *         Date 2016/10/30.
 */
@Service
public class WalletService {

    private static final Logger logger = LoggerFactory.getLogger(WalletService.class);

    @Resource
    private WalletMapper walletMapper;

    @Transactional
    public void addMoney(String accountId, int type, int amount) {
        WalletExample example = new WalletExample();
        example.createCriteria().andAccountIdEqualTo(accountId);
        List<Wallet> walletList = walletMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(walletList)) {
            Wallet wallet = new Wallet();
            switch (type) {
                case CaliforniaSiteConstant.WalletType.TYPE_BENXI:
                    wallet.setBenXi(amount);
                    break;
                case CaliforniaSiteConstant.WalletType.TYPE_RECOMMEND:
                    wallet.setRecReward(amount);
                    break;
                case CaliforniaSiteConstant.WalletType.TYPE_MANAGE:
                    wallet.setManageReward(amount);
                    break;
            }
            wallet.setAccountId(accountId);
            walletMapper.insert(wallet);
            return;
        }
        Wallet wallet = walletList.get(0);
        switch (type) {
            case CaliforniaSiteConstant.WalletType.TYPE_BENXI:
                wallet.setBenXi(wallet.getBenXi() + amount);
                break;
            case CaliforniaSiteConstant.WalletType.TYPE_RECOMMEND:
                wallet.setRecReward(wallet.getRecReward() + amount);
                break;
            case CaliforniaSiteConstant.WalletType.TYPE_MANAGE:
                wallet.setManageReward(wallet.getManageReward() + amount);
                break;
        }
        walletMapper.updateByPrimaryKey(wallet);
        logger.info("account {} add amount {}, income type {}", accountId, amount, type);
    }
}
